<?php
require '../model/Db.php';
$Db = Db::getInstance();
$user_data = $Db->islogin();
$w_arr = ['content','module','follow'];
if($user_data && in_array($_GET['w'], $w_arr) && is_numeric($_GET['id'])){
	switch ($_GET['w']) {
		case 'content':
			udcollect('content',$_GET['id'],$user_data,'cids',$Db);
			break;
		
		case 'module':
			udcollect('module',$_GET['id'],$user_data,'mids',$Db);
			break;

		case 'follow':
			$other_data = $Db->find([
				table => ['bbs_user'],
				where => "id = {$_GET['id']}"
			])[0];
			if($other_data){
				header('Content-Type:application/json;charset=utf8');
				//自己的my_follow
				$my_follow = json_decode($user_data['my_follow']);
				//对方的follow_me
				$follow_me = json_decode($other_data['follow_me']);
				if(in_array($other_data['id'], $my_follow->uids)){
					//删除
					$in = false;

					$index = array_search($other_data['id'], $my_follow->uids);
					array_splice($my_follow->uids,$index,1);

					$index2 = array_search($user_data['id'], $follow_me->uids);
					array_splice($follow_me->uids,$index2,1);
				}else{
					//添加
					$in = true;

					array_push($my_follow->uids,$other_data['id']);

					array_push($follow_me->uids,$user_data['id']);
				}
				$new_json = json_encode($my_follow);
				$new_json2 = json_encode($follow_me);
				//改自己
				$Db->update([
					table => 'bbs_user',
					map => [
						my_follow => $new_json
					],
					where => "id = {$user_data['id']}"
				]);
				//改对方
				$Db->update([
					table => 'bbs_user',
					map => [
						follow_me => $new_json2
					],
					where => "id = {$other_data['id']}"
				]);
				if($in){
					echo json_encode([sign => 'in']);
				}else{
					echo json_encode([sign => 'out']);
				}
			}else{
				deny();
			}
			break;
	}
	$Db->close();
}else{
	deny();
}
function deny(){
	http_response_code(404);
	echo '<h1 style="color:#337ab7">千呼万唤始出来,犹抱琵琶半遮面</h1>';
}
function udcollect($table,$id,$user_data,$ids,$Db){
			$isExist = $Db->find([
				table => [$table],
				where => "id = {$id}"
			])[0];
			if($isExist){
				header('Content-Type:application/json;charset=utf8');
				$my_follow = json_decode($user_data['my_follow']);
				if(in_array($id, $my_follow->$ids)){
					//删除
					$in = false;
					$index = array_search($id, $my_follow->$ids);
					array_splice($my_follow->$ids,$index,1);
				}else{
					//添加
					$in = true;
					array_push($my_follow->$ids,$id);
				}
				$new_json = json_encode($my_follow);
				$Db->update([
					table => 'bbs_user',
					map => [
						my_follow => $new_json
					],
					where => "id = {$user_data['id']}"
				]);
				if($table == 'module'){
					$val = $in ? '#collect_num+1#':'#collect_num-1#';
					$Db->update([
						table => 'module',
						map => [
							collect_num => $val
						],
						where => "id = {$id}"
					]);
				}
				if($in){
					echo json_encode([sign => 'in']);
				}else{
					echo json_encode([sign => 'out']);
				}
			}else{
				deny();
			}
}